package org.newcih.util;

import org.newcih.pojo.Box;
import org.newcih.pojo.BoxRow;

import java.awt.*;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Box文件的工具类
 *
 * @author newcih
 * @version 2018-01-29
 */
public class BoxUtils {

    public static final String EOL               = "\n";
    public static final String SPACE             = " ";
    public static final int    BOX_ROW_LINE_SIZE = 40;

    /**
     * 更新box文件的value值序列
     *
     * @param boxFile
     * @param valueList
     * @return
     */
    public static void updateBoxFileWithValue(File boxFile, List<String> valueList) throws Exception {
        Box box = fileToBox(boxFile);
        // 两者数目匹配，则可以更新
        System.out.println("两者数目");
        System.out.println(box.getBoxRowList().size());
        System.out.println(valueList.size());
        System.out.println("两者数目");
        if (box.getBoxRowList().size() == valueList.size()) {
            for (int i = 0; i < valueList.size(); i++) {
                box.getBoxRowList().get(i).setValue(valueList.get(i));
            }
            System.out.println("更新box文件成功");
        }
        // 重写box文件
        BoxUtils.boxToFile(box, boxFile.getPath());
    }

    /**
     * 将box文件解析为box对象
     *
     * @param boxFile
     * @return
     */
    public static Box fileToBox(File boxFile) throws Exception {
        Box          box        = new Box();
        List<BoxRow> boxRowList = new ArrayList<>();
        String       content    = FileUtils.readTextFile(boxFile);
        for (String line : content.split("\n")) {
            if (line != null && line.trim().length() > 0) {
                BoxRow boxRow = lineToBoxRow(line);
                boxRowList.add(boxRow);
            }
        }
        box.setBoxRowList(boxRowList);
        return box;
    }

    /**
     * 将box对象写入文件
     *
     * @param box
     * @return
     */
    public static File boxToFile(Box box, String fileName) {
        File newFile = new File(fileName);
        FileUtils.createFile(newFile);

        // 解析box
        if (box == null || box.getBoxRowList().size() == 0) {
            return newFile;
        }
        StringBuilder stringBuilder = new StringBuilder(BOX_ROW_LINE_SIZE * box.getBoxRowList().size());
        for (BoxRow row : box.getBoxRowList()) {
            String line = BoxUtils.boxRowToLine(row);
            stringBuilder.append(line).append(EOL);
        }

        // 写入box文件
        try {
            FileUtils.writeTextFile(newFile, stringBuilder.toString());
        } catch (Exception e) {
            System.err.println("将box对象序列化为文件失败!");
            return newFile;
        }

        return newFile;
    }

    /**
     * 将BoxRow对象解析为一行字符串（识别图块设置为图片大小，则图块无法生效[jTessBoxEditor工具下图块生成失败]，
     * 所以这里将BoxRow对象的坐标和大小作减1处理）
     *
     * @param boxRow
     * @return
     */
    public static String boxRowToLine(BoxRow boxRow) {
        StringBuilder stringBuilder = new StringBuilder(BOX_ROW_LINE_SIZE);
        stringBuilder.append(boxRow.getValue()).append(SPACE).append(boxRow.getRectangle().x + 1).append(SPACE)
                     .append(boxRow.getRectangle().y + 1).append(SPACE).append(boxRow.getRectangle().width - 1)
                     .append(SPACE).append(boxRow.getRectangle().height - 1).append(SPACE).append(boxRow.getIndex());

        return stringBuilder.toString();
    }

    /**
     * 将一行字符串解析为BoxRow对象
     *
     * @param line
     * @return
     */
    public static BoxRow lineToBoxRow(String line) {
        BoxRow    boxRow    = new BoxRow();
        Rectangle rectangle = new Rectangle();
        if (line == null || line.trim().length() == 0) {
            return boxRow;
        }

        String[] s = line.split(" ");
        boxRow.setValue(s[0]);
        boxRow.setIndex(Integer.parseInt(s[5]));
        rectangle.x = Integer.parseInt(s[1]);
        rectangle.y = Integer.parseInt(s[2]);
        rectangle.width = Integer.parseInt(s[3]);
        rectangle.height = Integer.parseInt(s[4]);
        boxRow.setRectangle(rectangle);

        return boxRow;
    }

    public static void main(String[] args) throws Exception {
        List<String> values = Arrays.asList("t", "t", "t", "t", "t", "y", "u", "i", "p", "[");
        File boxF = new File(
                "/home/newcih/Tesseract/D/d4d36446-3ab8-47cb-b6ac-0aaa5b2356eb/d4d36446-3ab8-47cb-b6ac-0aaa5b2356eb.box");
        updateBoxFileWithValue(boxF, values);
    }
}
